package buildcode.util;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import buildcode.Context;

public class VelocityUtil {
    static {
        try {
            Enumeration<URL> classPathRoots = VelocityUtil.class.getClassLoader().getResources("");
            URL configPath = VelocityUtil.class.getClassLoader().getResource("velocity.properties");
            File configFile = new File(configPath.toURI());
            String relateTplPath = getPath(configFile);
            List<String> resourceLoaderFilePaths = new ArrayList<String>();
            while (classPathRoots.hasMoreElements()) {
                File rootfile = new File(classPathRoots.nextElement().toURI());
                if (configFile.getAbsolutePath().startsWith(rootfile.getAbsolutePath())) {
                    resourceLoaderFilePaths = Stream.of(relateTplPath.split(",")).map(v -> rootfile.getAbsolutePath() + File.separator + relateTplPath).collect(Collectors.toList());
                    break;
                }
            }
            Properties temp = new Properties();
            temp.setProperty("resource.loader.file.path", StringUtils.join(resourceLoaderFilePaths, ","));
            Velocity.init(temp);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public static String render(String tpl, Object info, Map<String, Object> utils) {
        VelocityContext context = new VelocityContext();
        context.put("info", info);
        context.put("CommonUtil", CommonUtil.class);
        context.put("Context", Context.class);
        if (utils != null) {
            utils.forEach((k, v) -> context.put(k, v));
        }
        StringWriter w = new StringWriter();
        Velocity.mergeTemplate(tpl, "utf-8", context, w);
        return w.toString();
    }

    public static String render(String tpl, Object info) {
        return render(tpl, info, null);
    }

    private static String getPath(File file) throws IOException, URISyntaxException {
        if (file != null) {
            Properties velocityConfig = new Properties();
            velocityConfig.load(new FileReader(file));
            return velocityConfig.getProperty("path");
        }
        return "";

    }

}
